package com.ljz.controller;

import com.github.pagehelper.PageInfo;
import com.ljz.entity.Role;
import com.ljz.entity.User;
import com.ljz.service.RoleService;
import com.ljz.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private RoleService roleService;
    @Autowired
    private UserService userService;

    @RequestMapping("/register")
    public String register(@RequestBody User user) {
        return userService.register(user)?"true":"false";
    }
    @RequestMapping("/login")
    public String login(@RequestBody User user,HttpSession session) {
        System.out.println(user);
        if (userService.login(user)){
            session.setAttribute("user", user);
            return "true";
        }else
            return "false";
    }
    @RequestMapping("/getUsername")
    public User getUsername(HttpSession session){
        User user = (User) session.getAttribute("user");
        if (user != null){
            user.setPassword("");
        }
        return user;
    }
    @RequestMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute("user");
        return "true";
    }
    @RequestMapping("/checkName")
    public String checkName(String username){
        boolean result = userService.checkUsername(username);
        if (result) {
            return "true";
        } else
            return "false";
    }

    @RequestMapping("/deleteUsers")
    public String deleteUsers(@RequestBody List<Integer> ids){
        int result = userService.deleteUsers(ids);
        if (result > 0) {
            return "true";
        }
        return "false";
    }
    @RequestMapping("/getAllRole")
    public List<Role> getAllRole(){
        List<Role> roles = roleService.getRoles();
        return roles;
    }
    @RequestMapping("/editUser")
    public String editUser(@RequestBody User user,HttpSession session){
        session.setAttribute("upuser", user);
        return "true";
    }
    @RequestMapping("/getUserInfo")
    public User getUserInfo(HttpSession session){
        return (User) session.getAttribute("upuser");
    }
    @RequestMapping("/updateUser")
    public String updateUser(@RequestBody User user,HttpSession session){
        session.removeAttribute("upuser");
        return userService.updateUser(user)>0?"true":"false";
    }
    @RequestMapping("/getUsersByPage")
    public PageInfo<User> getUsersByPage(String username ,Integer currentPage, Integer pageSize){
        return userService.findUsers(username, currentPage,pageSize);
    }

}
